package Dao.Impl;

import Dao.CartDao;
import Domain.Cart;
import JDBCUtils.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class CartDaoImpl implements CartDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public List<Cart> FindCartByUserid(int id) {
        String sql = "select\n" +
                " t.id,t.cartid,t.productid,t1.picture,t1.name,t1.price,t.cnum,t1.num,t.totalprice\n" +
                "from\n" +
                " t_cart_product_relation t\n" +
                "join\n" +
                " product t1\n" +
                "on\n" +
                " t.productid = t1.id\n" +
                "where\n" +
                " t.cartid=?";
        List<Cart> result=null;
        try {
            result = template.query(sql,new BeanPropertyRowMapper<>(Cart.class),id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void DelCartItem(int id) {
        String sql = "delete from t_cart_product_relation where id=?";
        template.update(sql,id);
    }

    @Override
    public void AddCart(int uid, int pid, Double price) {
        String sql = "insert into t_cart_product_relation(id,cartid,productid,cnum,totalprice) values(null,?,?,1,?)";
        template.update(sql,uid,pid,price);
    }

    @Override
    public List<Cart> FindCartItemById(int id) {
        String sql ="select\n" +
                " t.id,t.cartid,t.productid,t1.picture,t1.name,t1.price,t.cnum,t1.num,t.totalprice\n" +
                "from\n" +
                " t_cart_product_relation t\n" +
                "join\n" +
                " product t1\n" +
                "on\n" +
                " t.productid = t1.id\n" +
                "where\n" +
                " t.id=?";
        List<Cart> result = null;
        try {
            result = template.query(sql,new BeanPropertyRowMapper<>(Cart.class),id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void UpdateCartItemNumById(int id, int num ,Double total) {
        String sql ="update t_cart_product_relation set cnum=?,totalprice=? where id=?";
        template.update(sql,num,total,id);
    }


}
